'use client';
import { useAuthStore2 } from '../store/useAuthStore2';
import { Toast } from 'antd-mobile';
import dd from 'dingtalk-jsapi';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useSWRConfig } from 'swr';
import { authApi } from '@/api/auth';

export const useAuth = () => {
	const getToken = useAuthStore2(s => s.getToken);
	const setToken = useAuthStore2(s => s.setToken);
	const token = useAuthStore2(s => s.token);
	const router = useRouter();
	const { mutate } = useSWRConfig();
    useEffect(() => {
		if (typeof window === 'undefined') {
			return;
		}
		const urlObj = new URL(window.location.href);
        const urlToken = urlObj.searchParams.get('wms_token');
		if (urlToken) {
			urlObj.searchParams.delete('wms_token');
			router.replace(
				window.location.pathname + '?' + urlObj.searchParams.toString()
			);
			setToken(urlToken);
			return;
        }
		if (token) return;
		const localToken = getToken();
		if (!localToken) {
			if (dd.env.platform === 'notInDingTalk') {
				Toast.show('请登录/或使用钉钉查看');
				return;
			}

			dd.runtime.permission.requestAuthCode({
				corpId: 'dingfe7f0f8400f595ecf2c783f7214b6d69',
				// @ts-ignore
				onSuccess: function (result: { code: string }) {
					mutate(result.code, authApi(result.code))
						.then(res => {
							setToken(res?.wms_token || '');
						})
						.catch(e => {
							console.log(e);
						});
				},
				onFail: function (err: Error) {
					Toast.show(err.message);
				}
			});
		}
	}, [token]);
	return token;
};

